package io.binghe.seckill.interfaces.interceptor;

import cn.hutool.core.util.StrUtil;
import io.binghe.seckill.domain.code.HttpCode;
import io.binghe.seckill.domain.constans.SeckillConstants;
import io.binghe.seckill.domain.exception.SeckillException;
import io.binghe.seckill.infrastructure.shiro.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: Dragon
 * @since: 2024/1/14 19:13
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    private static final String USER_ID = "userId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Object userIdObj = request.getAttribute(USER_ID);
        if(userIdObj != null) {
            return true;
        }

        String token = request.getHeader(SeckillConstants.TOKEN_HEADER_NAME);
        if(StrUtil.isEmpty(token)) {
            throw new SeckillException(HttpCode.USER_NOT_LOGIN);
        }

        Long userId = JwtUtils.getUserId(token);
        if(userId == null) {
            throw new SeckillException(HttpCode.USER_NOT_LOGIN);
        }

        HttpServletRequestWrapper httpServletRequestWrapper = new HttpServletRequestWrapper(request);
        httpServletRequestWrapper.setAttribute(USER_ID, userId);
        return true;
    }
}
